package com.miku.project.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.miku.mikuapiclientsdk.exception.ApiException;
import com.miku.mikuapiclientsdk.model.request.CurrencyRequest;
import com.miku.mikuapiclientsdk.model.response.ResultResponse;
import com.miku.mikuapiclientsdk.service.ApiService;

import com.miku.project.model.dto.interfaceinfo.ResponseParamsField;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import com.miku.mikuapiclientsdk.client.MikuApiClient;
import com.miku.mikuapicommon.model.entity.InterfaceInfo;
import com.miku.mikuapicommon.model.entity.User;
import com.miku.project.annotation.AuthCheck;
import com.miku.project.common.*;
import com.miku.project.constant.CommonConstant;
import com.miku.project.exception.BusinessException;
import com.miku.project.model.dto.interfaceinfo.*;
import com.miku.project.model.enums.InterfaceStatusEnum;
import com.miku.project.model.vo.UserVO;
import com.miku.project.service.InterfaceInfoService;
import com.miku.project.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.miku.project.constant.UserConstant.ADMIN_ROLE;

/**
 * 接口管理
 *
 * @author <a href="https://gitee.com/deng-taotao-eee">miku</a>
 * @from <a href=""></a>
 */
@RestController
@RequestMapping("/interfaceInfo")
@Slf4j
@Api(tags = "接口管理")
public class InterfaceInfoController {

    @Resource
    private InterfaceInfoService interfaceInfoService;

    @Resource
    private UserService userService;

    @Resource
    private MikuApiClient mikuApiClient;
    @Resource
    private ApiService apiService;

    private final Gson gson = new Gson();

    // region 增删改查

    /**
     * 添加接口信息
     *
     * @param interfaceInfoAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    @AuthCheck(mustRole = ADMIN_ROLE)
    @ApiOperation("添加接口信息")
    public BaseResponse<Long> addInterfaceInfo(@RequestBody InterfaceInfoAddRequest interfaceInfoAddRequest, HttpServletRequest request) {
        if (interfaceInfoAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 创建接口信息对象
        InterfaceInfo interfaceInfo = new InterfaceInfo();
        // 如果接口添加请求中的请求参数不为空
        if (CollectionUtils.isNotEmpty(interfaceInfoAddRequest.getRequestParams())) {
            // 过滤出请求参数字段，并且字段名不为空
            List<RequestParamsField> requestParamsFields = interfaceInfoAddRequest.getRequestParams()
                    .stream().filter(filed -> StringUtils.isNotBlank(filed.getFieldName()))
                    .collect(Collectors.toList());
            // 将请求参数字段转换为JSON字符串
            String requestParams = JSONUtil.toJsonStr(requestParamsFields);
            // 设置接口信息的请求参数
            interfaceInfo.setRequestParams(requestParams);
        }
        if (CollectionUtils.isNotEmpty(interfaceInfoAddRequest.getResponseParams())) {
            // 过滤出请求参数字段，并且字段名不为空
            List<ResponseParamsField> responseParamsFields = interfaceInfoAddRequest.getResponseParams()
                    .stream().filter(filed -> StringUtils.isNotBlank(filed.getFieldName()))
                    .collect(Collectors.toList());
            // 将请求参数字段转换为JSON字符串
            String requestParams = JSONUtil.toJsonStr(responseParamsFields);
            // 设置接口信息的请求参数
            interfaceInfo.setRequestParams(requestParams);
        }
        // 设置接口信息的其他字段
        BeanUtils.copyProperties(interfaceInfoAddRequest, interfaceInfo);
        //校验
        interfaceInfoService.validInterfaceInfo(interfaceInfo, true);
        UserVO loginUser = userService.getLoginUser(request);
        interfaceInfo.setUserId(loginUser.getId());
        // 保存到数据库
        boolean save = interfaceInfoService.save(interfaceInfo);
        if (!save) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
        return ResultUtils.success(interfaceInfo.getId());
    }

    /**
     * 删除接口信息
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    @ApiOperation("删除接口信息")
    public BaseResponse<Boolean> deleteInterfaceInfo(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        UserVO user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        InterfaceInfo oldInterfaceInfo = interfaceInfoService.getById(id);
        if (oldInterfaceInfo == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        // 仅本人或管理员可删除
        if (!oldInterfaceInfo.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = interfaceInfoService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新
     *
     * @param interfaceInfoUpdateRequest
     * @param request
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = ADMIN_ROLE)
    @Transactional(rollbackFor = Exception.class)
    public BaseResponse<Boolean> updateInterfaceInfo(@RequestBody InterfaceInfoUpdateRequest interfaceInfoUpdateRequest,
                                                     HttpServletRequest request) {
        //校验参数
        if (interfaceInfoUpdateRequest == null || interfaceInfoUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        InterfaceInfo interfaceInfo = new InterfaceInfo();
        if (CollectionUtils.isNotEmpty(interfaceInfoUpdateRequest.getRequestParams())) {
            // 过滤出请求参数字段，并且字段名不为空
            List<RequestParamsField> requestParamsFields = interfaceInfoUpdateRequest.getRequestParams()
                    .stream().filter(filed -> StringUtils.isNotBlank(filed.getFieldName()))
                    .collect(Collectors.toList());
            // 将请求参数字段转换为JSON字符串
            String requestParams = JSONUtil.toJsonStr(requestParamsFields);
            // 设置接口信息的请求参数
            interfaceInfo.setRequestParams(requestParams);
        } else {
            interfaceInfo.setRequestParams("[]");
        }
        if (CollectionUtils.isNotEmpty(interfaceInfoUpdateRequest.getResponseParams())) {
            // 过滤出请求参数字段，并且字段名不为空
            List<ResponseParamsField> responseParamsFields = interfaceInfoUpdateRequest.getResponseParams()
                    .stream().filter(filed -> StringUtils.isNotBlank(filed.getFieldName()))
                    .collect(Collectors.toList());
            // 将请求参数字段转换为JSON字符串
            String requestParams = JSONUtil.toJsonStr(responseParamsFields);
            // 设置接口信息的请求参数
            interfaceInfo.setRequestParams(requestParams);
        } else {
            interfaceInfo.setResponseParams("[]");
        }
        BeanUtils.copyProperties(interfaceInfoUpdateRequest, interfaceInfo);
        //参数校验
        interfaceInfoService.validInterfaceInfo(interfaceInfo, false);
        UserVO loginUser = userService.getLoginUser(request);
        Long id = loginUser.getId();
        User user = userService.getById(id);
        if (user == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        //仅本人或者管理员可以修改
        if (!userService.isAdmin(request) && !user.getId().equals(interfaceInfo.getUserId())) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }

        boolean result = interfaceInfoService.updateById(interfaceInfo);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取接口信息
     *
     * @param id
     * @return
     */
    @GetMapping("/get")
    @ApiOperation("根据id获取接口信息")
    public BaseResponse<InterfaceInfo> getInterfaceInfoById(long id) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        InterfaceInfo interfaceInfo = interfaceInfoService.getById(id);
        return ResultUtils.success(interfaceInfo);
    }

    /**
     * 获取列表（仅管理员可使用）
     *
     * @param interfaceInfoQueryRequest
     * @return
     */
    @AuthCheck(mustRole = ADMIN_ROLE)
    @GetMapping("/list")
    public BaseResponse<List<InterfaceInfo>> listInterfaceInfo(InterfaceInfoQueryRequest interfaceInfoQueryRequest) {
        InterfaceInfo interfaceInfoQuery = new InterfaceInfo();
        if (interfaceInfoQueryRequest != null) {
            BeanUtils.copyProperties(interfaceInfoQueryRequest, interfaceInfoQuery);
        }
        QueryWrapper<InterfaceInfo> queryWrapper = new QueryWrapper<>(interfaceInfoQuery);
        List<InterfaceInfo> interfaceInfoList = interfaceInfoService.list(queryWrapper);
        return ResultUtils.success(interfaceInfoList);
    }

    /**
     * 分页获取列表
     *
     * @param interfaceInfoQueryRequest
     * @param request
     * @return
     */
    @GetMapping("/list/page")
    @ApiOperation("分页获取接口信息列表")
    public BaseResponse<Page<InterfaceInfo>> listInterfaceInfoByPage(InterfaceInfoQueryRequest interfaceInfoQueryRequest, HttpServletRequest request) {
        if (interfaceInfoQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        InterfaceInfo interfaceInfo = new InterfaceInfo();
        BeanUtils.copyProperties(interfaceInfoQueryRequest, interfaceInfo);

        String name = interfaceInfoQueryRequest.getName();
        String returnFormat = interfaceInfoQueryRequest.getReturnFormat();
        String url = interfaceInfoQueryRequest.getUrl();
        Integer reduceScore = interfaceInfoQueryRequest.getReduceScore();
        String method = interfaceInfoQueryRequest.getMethod();
        String description = interfaceInfoQueryRequest.getDescription();
        Integer status = interfaceInfoQueryRequest.getStatus();

        long current = interfaceInfoQueryRequest.getCurrent();
        long pageSize = interfaceInfoQueryRequest.getPageSize();
        if (current < 0 || pageSize <= 0) {
            //设置默认值
            current = 1L;
            pageSize = 10L;
        }
        String sortField = interfaceInfoQueryRequest.getSortField();
        String sortOrder = interfaceInfoQueryRequest.getSortOrder();
        //限制爬虫
        if (pageSize > 50) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        QueryWrapper<InterfaceInfo> queryWrapper = new QueryWrapper<>();
        //根据名称和描述模糊查询
        if (!StringUtils.isBlank(name) && !StringUtils.isBlank(description)) {
            queryWrapper.and(wq -> wq.like("name", name)).or()
                    .like("description", description);
        }

        queryWrapper
                //根据url模糊查询
                .like(StringUtils.isNotBlank(url), "url", url)
                //更具返回参数模糊查询
                .like(StringUtils.isNotBlank(returnFormat), "returnFormat", returnFormat)
                //根据method查询
                .eq(StringUtils.isNotBlank(method), "method", method)
                //根据状态查询
                .eq(ObjectUtils.isNotEmpty(status), "status", status)
                .eq(ObjectUtils.isNotEmpty(reduceScore), "reduceScore", reduceScore);
        queryWrapper.orderBy(StringUtils.isNotBlank(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC), sortField);
        Page<InterfaceInfo> interfaceInfoPage = interfaceInfoService.page(new Page<>(current, pageSize), queryWrapper);
        User user = userService.isTourist(request);
        if (user == null || user.getUserRole().equals(ADMIN_ROLE)) {
            List<InterfaceInfo> interfaceInfoList = interfaceInfoPage.getRecords().stream()
                    .filter(x -> x.getStatus().equals(InterfaceStatusEnum.ONLINE.getValue())).collect(Collectors.toList());
            interfaceInfoPage.setRecords(interfaceInfoList);
        }

        return ResultUtils.success(interfaceInfoPage);
    }


    /**
     * 按搜索文本查询数据
     *
     * @param infoSearchTextRequest
     * @return
     */
    @GetMapping("/get/searchText")
    @ApiOperation("按搜索文本查询数据")
    public BaseResponse<Page<InterfaceInfo>> listInterfaceInfoBySearchTextPage(InterfaceInfoSearchTextRequest infoSearchTextRequest,HttpServletRequest request) {
        if (infoSearchTextRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        InterfaceInfo interfaceInfo = new InterfaceInfo();
        BeanUtils.copyProperties(infoSearchTextRequest, interfaceInfo);

        String searchText = infoSearchTextRequest.getSearchText();
        long pageSize = infoSearchTextRequest.getPageSize();
        long current = infoSearchTextRequest.getCurrent();
        String sortField = infoSearchTextRequest.getSortField();
        String sortOrder = infoSearchTextRequest.getSortOrder();


        QueryWrapper<InterfaceInfo> queryWrapper = new QueryWrapper<>();
        //根据搜索文本查询
        if (StringUtils.isNotBlank(searchText)) {
            queryWrapper.and(x -> x.like(StringUtils.isNotBlank(searchText), "name", searchText))
                    .or()
                    .like(StringUtils.isNotBlank(searchText), "description", searchText);
        }
        queryWrapper.orderBy(StringUtils.isNotBlank(sortField),sortOrder.equals(CommonConstant.SORT_ORDER_ASC),sortField);
        Page<InterfaceInfo> interfaceInfoPage=interfaceInfoService.page(new Page<>(current, pageSize), queryWrapper);
        //不是管理员只能查看线上的
       if (!userService.isAdmin(request)){
           List<InterfaceInfo> interfaceInfoList=interfaceInfoPage.getRecords().stream().filter(
                   x->x.getStatus().equals(InterfaceStatusEnum.ONLINE.getValue())
           ).collect(Collectors.toList());
           interfaceInfoPage.setRecords(interfaceInfoList);
       }

       return ResultUtils.success(interfaceInfoPage);
    }

    // endregion

    /**
     * 发布
     *
     * @param idRequest
     * @param request
     * @return
     */
    @PostMapping("/online")
    @AuthCheck(mustRole = ADMIN_ROLE)
    @ApiOperation("发布接口")
    public BaseResponse<Boolean> onlineInterfaceInfo(@RequestBody IdRequest idRequest,
                                                     HttpServletRequest request) {
        if (idRequest == null || idRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long id = idRequest.getId();
        // 判断是否存在
        InterfaceInfo oldInterfaceInfo = interfaceInfoService.getById(id);
        if (oldInterfaceInfo == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        // 仅本人或管理员可修改
        InterfaceInfo interfaceInfo = new InterfaceInfo();
        interfaceInfo.setId(id);
        interfaceInfo.setStatus(InterfaceStatusEnum.ONLINE.getValue());
        boolean result = interfaceInfoService.updateById(interfaceInfo);
        return ResultUtils.success(result);
    }

    /**
     * 下线
     *
     * @param idRequest
     * @param request
     * @return
     */
    @PostMapping("/offline")
    @AuthCheck(mustRole = ADMIN_ROLE)
    @ApiOperation("下线接口")
    public BaseResponse<Boolean> offlineInterfaceInfo(@RequestBody IdRequest idRequest,
                                                      HttpServletRequest request) {
        if (idRequest == null || idRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long id = idRequest.getId();
        // 判断是否存在
        InterfaceInfo oldInterfaceInfo = interfaceInfoService.getById(id);
        if (oldInterfaceInfo == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        // 仅本人或管理员可修改
        InterfaceInfo interfaceInfo = new InterfaceInfo();
        interfaceInfo.setId(id);
        interfaceInfo.setStatus(InterfaceStatusEnum.OFFLINE.getValue());
        boolean result = interfaceInfoService.updateById(interfaceInfo);
        return ResultUtils.success(result);
    }

    /**
     * 测试调用
     *
     * @param interfaceInfoInvokeRequest
     * @param request
     * @return
     */
    @PostMapping("/invoke")
    @ApiOperation("测试调用")
    @Transactional(rollbackFor = Exception.class)
    public BaseResponse<Object> invokeInterfaceInfo(@RequestBody InterfaceInfoInvokeRequest interfaceInfoInvokeRequest,
                                                    HttpServletRequest request) {
        if (interfaceInfoInvokeRequest == null || interfaceInfoInvokeRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long id = interfaceInfoInvokeRequest.getId();
        // 判断是否存在
        InterfaceInfo infoServiceById = interfaceInfoService.getById(id);
        if (infoServiceById == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        if (!infoServiceById.getStatus().equals(InterfaceStatusEnum.ONLINE.getValue())){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"接口未开启");
        }
        //构建请求参数
        List<InterfaceInfoInvokeRequest.Field> fieldList = interfaceInfoInvokeRequest.getRequestParams();
        String requestParam="{}";
        if (fieldList!=null && fieldList.size()>0){
            JsonObject jsonObject = new JsonObject();
            for (InterfaceInfoInvokeRequest.Field field : fieldList) {
                jsonObject.addProperty(field.getFieldName(),field.getValue());
            }
            requestParam=gson.toJson(jsonObject);
        }
        //调用接口
        Map<String,Object> params=new Gson().fromJson(requestParam,new TypeToken<Map<String,Object>>(){}.getType());
        UserVO loginUser = userService.getLoginUser(request);
        String accessKey = loginUser.getAccessKey();
        String secretKey = loginUser.getSecretKey();

        try {
            MikuApiClient mikuApiClient=new MikuApiClient(accessKey,secretKey);

            CurrencyRequest currencyRequest=new CurrencyRequest();
            currencyRequest.setMethod(infoServiceById.getMethod());
            currencyRequest.setPath(infoServiceById.getUrl());
            currencyRequest.setRequestParams(params);
            ResultResponse response = apiService.request(mikuApiClient, currencyRequest);
            return ResultUtils.success(response.getData());
        } catch (Exception e) {
            log.error("调用接口失败",e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,e.getMessage());
        }
    }


    /**
     * 更换接口头像url
     * @param infoUpdateAvatarRequest
     * @param request
     * @return
     */
    @PostMapping("/updateInterfaceInfoAvatar")
    @AuthCheck(mustRole = ADMIN_ROLE)
    public BaseResponse<Boolean> updateInterfaceInfoAvatarUrl(@RequestBody InterfaceInfoUpdateAvatarRequest infoUpdateAvatarRequest,HttpServletRequest request){
        if (ObjectUtils.anyNull(infoUpdateAvatarRequest,infoUpdateAvatarRequest.getAvatarUrl())){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"参数为空");
        }
        boolean update = interfaceInfoService.update(Wrappers.<InterfaceInfo>lambdaUpdate()
                .eq(InterfaceInfo::getId, infoUpdateAvatarRequest.getId())
                .set(InterfaceInfo::getAvatarUrl, infoUpdateAvatarRequest.getAvatarUrl()));
        return ResultUtils.success(update);
    }


}
